<template>
  <div class="">
    <!-- 页面标题和说明 -->
    <!-- 操作栏 -->
    <el-card shadow="never" class="mb-6 border-box">
      <el-form :inline="true" :model="queryParams" class="flex flex-wrap items-end h-[40px]">
        <el-form-item label="反馈类型">
          <el-select
            v-model="queryParams.type"
            placeholder="全部类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(value, key) in FeedbackTypeMaps"
              :key="key"
              :label="value"
              :value="key + 1"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="反馈状态">
          <el-select
            v-model="queryParams.state"
            placeholder="全部状态"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(value, key) in FeedbackStatusMaps"
              :key="key"
              :label="value"
              :value="key + 1"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="flex gap-2">
            <el-button type="primary" @click="handleSearch" :icon="Search"> 查询 </el-button>
            <el-button @click="resetQuery" :icon="Refresh"> 重置 </el-button>
            <!-- <el-button type="success" @click="toCreateFeedback" :icon="Plus">
                            新增反馈
                        </el-button> -->
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 数据统计卡片 -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4 mb-6">
      <!-- 总反馈数 -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-900 dark:to-blue-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-blue-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-document text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">总反馈数</div>
            <CountTo class="stats-card__count text-xl font-bold truncate" :endVal="statistics.total" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>

      <!-- 待处理 -->
      <!-- shadow="hover" -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-red-50 to-red-100 dark:from-red-900 dark:to-red-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-red-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-warning text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">待处理</div>
            <CountTo class="stats-card__count text-xl font-bold truncate" :endVal="statistics.totalPending" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>

      <!-- 处理中 -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-yellow-50 to-yellow-100 dark:from-yellow-900 dark:to-yellow-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-yellow-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-time text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">处理中</div>
            <CountTo class="stats-card__count text-xl font-bold truncate" :endVal="statistics.totalProcessing" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>

      <!-- 已解决 -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-green-50 to-green-100 dark:from-green-900 dark:to-green-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-green-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-checkmark text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">已解决</div>
            <CountTo class="stats-card__count text-xl font-bold truncate" :endVal="statistics.totalProcessed" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>

      <!-- 已关闭 -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-gray-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-close text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">已关闭</div>
            <CountTo class="stats-card__count text-xl font-bold truncate" :endVal="statistics.totalClosed" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格 -->
    <el-card shadow="never" class="border-box">
      <el-table
        v-loading="loading"
        :data="feedbackList"
        style="width: 100%"
        height="calc(100vh - 450px)"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="联系方式" width="150" align="center">
          <template #default="scope">
            <div class="text-sm">{{ scope.row.contactWay }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="反馈类型" width="120" align="center">
          <template #default="scope">
            <el-tag
              :type="getFeedbackTypeColor(FeedbackTypeMaps[parseInt(scope.row.type) - 1])"
              effect="light"
            >
              {{ FeedbackTypeMaps[parseInt(scope.row.type) - 1] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="反馈内容" min-width="250" show-overflow-tooltip>
          <template #default="scope">
            <div class="flex items-start">
              <div class="feedback-content">
                <div class="text-sm line-clamp-2">{{ scope.row.content }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="反馈来源" min-width="100" align="center">
          <template #default="scope">
            <div>{{ FeedbackSourceMaps[scope.row.source] }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="getFeedbackStatusColor(FeedbackStatusMaps[parseInt(scope.row.state) - 1])"
              effect="light"
            >
              {{ FeedbackStatusMaps[parseInt(scope.row.state) - 1] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="100" show-overflow-tooltip align="center">
          <template #default="scope">
            <div class="text-sm">
              {{ scope.row.remark }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" header-align="center">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleView(scope.row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button
              v-if="scope.row.state == 1"
              type="success"
              link
              size="small"
              @click="handleProcess(scope.row)"
            >
              <el-icon><Tools /></el-icon>
              处理
            </el-button>
            <el-button
              v-if="scope.row.state == 2 || scope.row.state == 1"
              type="warning"
              link
              size="small"
              @click="handleReply(scope.row)"
            >
              <el-icon><ChatLineRound /></el-icon>
              回复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="flex justify-center mt-5">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog v-model="replyDialogVisible" title="回复反馈" width="500px" destroy-on-close>
      <el-form :model="replyForm" label-width="80px">
        <el-form-item label="反馈内容" class="mb-4">
          <div class="p-3 bg-gray-50 rounded text-sm">{{ currentFeedback.content }}</div>
        </el-form-item>
        <el-form-item label="回复内容" prop="reply">
          <el-input
            v-model="replyForm.reply"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="replyForm.state" placeholder="请选择状态" disabled>
            <el-option
              v-for="(value, key) in FeedbackStatusMaps"
              :key="key"
              :label="value"
              :value="key"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">确认回复</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { CountTo } from 'vue3-count-to'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Refresh } from '@element-plus/icons-vue'
  import type { FeedbackType } from '@/types/feedback'
  import { FeedbackTypeEnum, FeedbackStatusEnum, FeedbackSourceEnum } from '@/types/feedback'
  import {
    scenicComplaintFeedbackGetComplaintFeedbackUsingPost,
    scenicComplaintFeedbackDisposeUpdateFeedbackDisposeUsingPut,
    scenicComplaintFeedbackDisposeSaveFeedbackDisposeUsingPost,
    scenicComplaintFeedbackStatisticsUsingGet
  } from '@/api/4a'

  const router = useRouter()

  // 查询参数
  const queryParams = reactive({
    type: '',
    state: ''
  })
  // 反馈类型
  const FeedbackTypeMaps = Object.keys(FeedbackTypeEnum).map(
    (key) => FeedbackTypeEnum[key as keyof typeof FeedbackTypeEnum]
  )

  // 状态类型
  const FeedbackStatusMaps = Object.keys(FeedbackStatusEnum).map(
    (key) => FeedbackStatusEnum[key as keyof typeof FeedbackStatusEnum]
  )

  // 反馈来源
  const FeedbackSourceMaps = Object.keys(FeedbackSourceEnum).map(
    (key) => FeedbackSourceEnum[key as keyof typeof FeedbackSourceEnum]
  )
  // 表格数据
  const feedbackList = ref<FeedbackType[]>([])
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  // 统计数据
  const statistics = ref({
    total: 0,
    // 已解决
    totalProcessed: 0,
    // 处理中
    totalProcessing: 0,
    // 待处理
    totalPending: 0,
    // 已关闭
    totalClosed: 0
  })

  // 回复对话框相关
  const replyDialogVisible = ref(false)
  const currentFeedback = ref<FeedbackType>({} as FeedbackType)
  const replyForm = reactive({
    reply: '',
    state: 3
  })

  // 获取反馈类型颜色
  const getFeedbackTypeColor = (type: string) => {
    switch (type) {
      case FeedbackTypeEnum.BUG:
        return 'danger'
      case FeedbackTypeEnum.SUGGESTION:
        return 'success'
      case FeedbackTypeEnum.COMPLAINT:
        return 'warning'
      case FeedbackTypeEnum.QUESTION:
        return 'info'
      default:
        return undefined
    }
  }

  // 获取反馈状态颜色
  const getFeedbackStatusColor = (state: string) => {
    switch (state) {
      case FeedbackStatusEnum.PENDING:
        return 'danger'
      case FeedbackStatusEnum.PROCESSING:
        return 'warning'
      case FeedbackStatusEnum.REPLIED:
        return 'success'
      case FeedbackStatusEnum.CLOSED:
        return 'info'
      default:
        return undefined
    }
  }

  // 组件挂载时获取数据
  onMounted(() => {;
    getFeedbackList()
  })

  // 获取反馈列表
  const getFeedbackList = async () => {
    loading.value = true
    let body = {
      current: currentPage.value,
      size: pageSize.value,
      ...queryParams,
      type: queryParams.type ? Number(queryParams.type) : undefined
    }
    scenicComplaintFeedbackGetComplaintFeedbackUsingPost({ body: body as any })
      .then((res: any) => {
        if (res.code === 0) {
          feedbackList.value = res.data.list
          total.value = res.data.total
          updateStatistics()
        } else {
          ElMessage.error(res.msg)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  // 更新统计数据
  const updateStatistics = () => {
    scenicComplaintFeedbackStatisticsUsingGet({ options: {} }).then((res: any) => {
      if (res.code === 0) {
        statistics.value = res.data
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  // 查询
  const handleSearch = () => {
    currentPage.value = 1
    getFeedbackList()
  }

  // 重置查询
  const resetQuery = () => {
    Object.keys(queryParams).forEach((key) => {
      queryParams[key as keyof typeof queryParams] = ''
    })
    currentPage.value = 1
    getFeedbackList()
  }

  // 创建反馈
  // const toCreateFeedback = () => {
  //   router.push('/feedback/FeedbackCreate')
  // }

  // 查看详情
  const handleView = (row: FeedbackType) => {
    router.push({
      path: '/feedback/detail',
      query: { id: row.id }
    })
  }

  // 处理反馈
  const handleProcess = (row: FeedbackType) => {
    ElMessageBox.confirm('确认开始处理该反馈?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        // 调用处理接口更新数据
        let body = {
          ...row,
          state: 2,
          feedbackId: row.id,
          current: currentPage.value,
          size: pageSize.value
        }
        scenicComplaintFeedbackDisposeUpdateFeedbackDisposeUsingPut({ body })
          .then((res: any) => {
            if (res.code === 0) {
              feedbackList.value = feedbackList.value.map((item) => {
                if (item.id === row.id) {
                  item.state = 2
                }
                return item
              })
              updateStatistics()
              ElMessage.success('状态已更新为处理中')
            } else {
              ElMessage.error(res.msg)
            }
          })
          .catch((error) => {
            ElMessage.error(error || '处理失败，请稍后重试')
          })
      })
      .catch(() => {})
  }

  // 回复反馈
  const handleReply = (row: FeedbackType) => {
    currentFeedback.value = { ...row }
    replyForm.reply = row.adminReply || ''
    replyForm.state = 2
    replyDialogVisible.value = true
  }

  // 提交回复
  const submitReply = () => {
    if (!replyForm.reply.trim()) {
      ElMessage.warning('请输入回复内容')
      return
    }
    replyDialogVisible.value = false
    currentFeedback.value.state = replyForm.state + 1
    currentFeedback.value.content = replyForm.reply
    let body = {
      ...currentFeedback.value,
      feedbackId: currentFeedback.value.id,
      userid: 9999,
      current: currentPage.value,
      size: pageSize.value
    }
    // 调用接口
    scenicComplaintFeedbackDisposeSaveFeedbackDisposeUsingPost({ body }).then((res: any) => {
      if (res.code == 0) {
        getFeedbackList()
        ElMessage.success('回复成功')
        updateStatistics()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  // 处理页码大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getFeedbackList()
  }

  // 处理页码变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getFeedbackList()
  }
</script>

<style lang="scss" scoped>
  .feedback-list {
    .feedback-content {
      .line-clamp-2 {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }
  }

  .stats-card {
    cursor: pointer;
    box-shadow: none;
    transition: transform 0.2s ease;

    &:hover {
      transform: translateY(-2px);
    }
  }
  .border-box {
    border-radius: 8px !important;
  }
</style>
